import { UnifiedProblemData, ProblemCategory } from '../types/analysis';

// 从API导入的类型
export interface TaskScanResultsIssue {
  ruleId: string;
  ruleName: string;
  issueType?: string;
  severity: 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO' | string;
  description?: string;
  suggestion?: string;
  sqlContent?: string;
  sourceFile?: string;
  fileName?: string;
  gitFileUrl?: string;
  lineNumber?: number;
  columnNumber?: number;
  originalSql?: string;
  suggestedSql?: string;
  statementNumber?: number;  // SQL语句编号
  
  // AI增强验证字段 (v4.2新增)
  ruleAnalysisConfirmed?: boolean;      // 规则分析是否被AI确认
  aiIssueDescription?: string;          // AI分析的问题描述
  aiConfidenceScore?: number;           // AI分析置信度
  optimizedSql?: string;                // AI优化后的完整SQL语句
  optimizationExplanation?: string;     // AI优化说明
  analysisEngine?: string;              // 分析引擎
  aiOptimized?: boolean;                // 是否经过AI优化
  aiVerificationDetails?: any;          // AI验证详情
  
  metadata?: {
    analysisEngine?: 'RULE_BASED' | 'LLM_BASED';
    analysisSource?: 'RULE' | 'LLM';
    confidence?: number;
    statementNumber?: number;  // 备选的语句编号位置
    [key: string]: any;
  };
}

/**
 * 将API返回的TaskScanResultsIssue数组转换为UnifiedProblemData数组
 * 这是TaskDetail页面需要的主要转换函数
 */
export const problemDataConverter = (issues: TaskScanResultsIssue[]): UnifiedProblemData[] => {
  return issues.map((issue, index) => {
    // 使用后端返回的statementNumber，如果没有则从metadata中获取，最后才回退到基于行号计算
    const statementNumber = issue.statementNumber || 
                           issue.metadata?.statementNumber || 
                           Math.ceil((issue.lineNumber || 1) / 10) || 1;
    
    // 确定分析源类型 - 优先从metadata获取，然后根据ruleId推断
    let analysisSource: 'RULE' | 'LLM' = 'RULE';
    if (issue.metadata?.analysisEngine === 'LLM_BASED') {
      analysisSource = 'LLM';
    } else if (issue.metadata?.analysisEngine === 'RULE_BASED') {
      analysisSource = 'RULE';
    } else if (issue.metadata?.analysisSource === 'LLM') {
      analysisSource = 'LLM';
    } else if (issue.metadata?.analysisSource === 'RULE') {
      analysisSource = 'RULE';
    } else if (issue.ruleId?.startsWith('AI_') || issue.ruleId?.includes('LLM')) {
      analysisSource = 'LLM';
    }
    
    const unifiedProblem: UnifiedProblemData = {
      id: `${issue.ruleId}_${index}`,
      statementNumber,
      ruleId: issue.ruleId,
      ruleName: issue.ruleName,
      issueType: issue.issueType || 'UNKNOWN',
      severity: issue.severity as 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO',
      category: (issue.issueType as ProblemCategory) || 'COMPATIBILITY',
      description: issue.description || '',
      suggestion: issue.suggestion || '',
      sqlContent: issue.sqlContent || '',
      sqlFragment: issue.sqlContent || '',
      lineNumber: issue.lineNumber || 0,
      columnNumber: issue.columnNumber || 0,
      analysisSource,
      confidence: issue.metadata?.confidence,
      originalCode: issue.originalSql || issue.sqlContent || '',
      suggestedCode: issue.suggestedSql || issue.suggestion || '',
      fileName: issue.fileName || issue.sourceFile,
      gitFileUrl: issue.gitFileUrl,
      
      // AI增强验证字段 (v4.2新增)
      ruleAnalysisConfirmed: issue.ruleAnalysisConfirmed,
      aiIssueDescription: issue.aiIssueDescription,
      aiConfidenceScore: issue.aiConfidenceScore,
      optimizedSql: issue.optimizedSql,
      optimizationExplanation: issue.optimizationExplanation,
      analysisEngine: issue.analysisEngine,
      aiOptimized: issue.aiOptimized,
      aiVerificationDetails: issue.aiVerificationDetails
    };
    
    return unifiedProblem;
  });
};

/**
 * 将传统的问题分组格式转换为统一的问题数据格式
 */
export interface LegacyProblem {
  id: string;
  lineNumber: number;
  columnNumber: number;
  severity: 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
  category: string;
  description: string;
  suggestion: string;
  ruleName?: string;
  originalCode?: string;
  suggestedCode?: string;
  sqlFragment?: string;
}

export interface LegacyProblemGroup {
  key: string;
  title: string;
  icon: React.ReactNode;
  count: number;
  items: LegacyProblem[];
  color: string;
}

/**
 * 将传统问题组格式转换为统一问题数据格式
 */
export const convertLegacyProblemsToUnified = (
  problemGroups: LegacyProblemGroup[],
  analysisSource: 'RULE' | 'LLM' = 'RULE'
): UnifiedProblemData[] => {
  const unifiedProblems: UnifiedProblemData[] = [];
  
  problemGroups.forEach(group => {
    group.items.forEach((item, index) => {
      // 计算SQL语句编号（简单基于行号）
      const statementNumber = Math.ceil(item.lineNumber / 10) || 1;
      
      const unifiedProblem: UnifiedProblemData = {
        id: item.id,
        statementNumber,
        ruleId: item.ruleName || `${analysisSource}${String(index + 1).padStart(3, '0')}`,
        ruleName: item.ruleName || `${analysisSource === 'RULE' ? '规则' : 'AI'}分析问题`,
        issueType: item.category,
        severity: item.severity,
        category: item.category as any,
        description: item.description,
        suggestion: item.suggestion,
        sqlContent: item.originalCode || '',
        sqlFragment: item.sqlFragment,
        lineNumber: item.lineNumber,
        columnNumber: item.columnNumber,
        analysisSource,
        originalCode: item.originalCode,
        suggestedCode: item.suggestedCode,
        groupKey: group.key,
        groupTitle: group.title,
        groupColor: group.color
      };
      
      unifiedProblems.push(unifiedProblem);
    });
  });
  
  return unifiedProblems;
};

/**
 * 计算SQL语句编号的辅助函数
 * 基于简单的启发式规则：每个SQL语句通常以关键字开始
 */
export const calculateStatementNumber = (sqlContent: string, lineNumber: number): number => {
  const lines = sqlContent.split('\n');
  let statementCount = 1;
  
  for (let i = 0; i < Math.min(lineNumber - 1, lines.length); i++) {
    const line = lines[i].trim().toUpperCase();
    // 检测SQL语句开始的关键字
    if (line.startsWith('SELECT') || 
        line.startsWith('INSERT') || 
        line.startsWith('UPDATE') || 
        line.startsWith('DELETE') ||
        line.startsWith('CREATE') ||
        line.startsWith('ALTER') ||
        line.startsWith('DROP') ||
        line.startsWith('WITH')) {
      statementCount++;
    }
  }
  
  return Math.max(1, statementCount - 1);
};

/**
 * 模拟AI分析结果的数据生成器（用于测试）
 */
export const generateMockAIProblems = (sqlContent: string): UnifiedProblemData[] => {
  const mockProblems: UnifiedProblemData[] = [];
  
  // 模拟一些AI分析发现的问题
  if (sqlContent.includes('ROWNUM')) {
    mockProblems.push({
      id: 'ai_001',
      statementNumber: 1,
      ruleId: 'AI0101', // 后台生成的虚拟ID
      ruleName: 'Oracle ROWNUM转换',
      issueType: 'SYNTAX',
      severity: 'HIGH',
      category: 'SYNTAX',
      description: 'Oracle的ROWNUM在目标数据库中不支持',
      suggestion: '使用LIMIT语句替代ROWNUM进行结果集限制，并将其移动到语句末尾',
      sqlContent: sqlContent,
      sqlFragment: 'WHERE ROWNUM <= 10',
      lineNumber: 3,
      columnNumber: 1,
      analysisSource: 'LLM',
      confidence: 95,
      originalCode: 'WHERE ROWNUM <= 10',
      suggestedCode: 'LIMIT 10'
    });
  }
  
  if (sqlContent.includes('NVL2')) {
    mockProblems.push({
      id: 'ai_002', 
      statementNumber: 1,
      ruleId: 'AI0102', // 后台生成的虚拟ID
      ruleName: 'NVL2函数转换',
      issueType: 'FUNCTION',
      severity: 'MEDIUM',
      category: 'FUNCTION',
      description: 'NVL2函数在目标数据库中不支持',
      suggestion: '使用CASE WHEN语句替代NVL2函数以实现相同的条件逻辑',
      sqlContent: sqlContent,
      sqlFragment: 'NVL2(u.email, u.email, \'N/A\')',
      lineNumber: 1,
      columnNumber: 20,
      analysisSource: 'LLM',
      confidence: 90,
      originalCode: 'NVL2(u.email, u.email, \'N/A\')',
      suggestedCode: 'CASE WHEN u.email IS NOT NULL THEN u.email ELSE \'N/A\' END'
    });
  }
  
  if (sqlContent.includes('CONNECT BY')) {
    mockProblems.push({
      id: 'ai_003',
      statementNumber: 2,
      ruleId: 'AI0201', // 后台生成的虚拟ID
      ruleName: 'Oracle递归查询转换',
      issueType: 'SYNTAX',
      severity: 'HIGH',
      category: 'SYNTAX',
      description: 'Oracle的CONNECT BY递归查询语法在目标数据库中不支持',
      suggestion: '使用WITH RECURSIVE公用表表达式重写递归查询以实现相同的层次结构遍历',
      sqlContent: sqlContent,
      sqlFragment: 'START WITH manager_id IS NULL CONNECT BY PRIOR employee_id = manager_id',
      lineNumber: 8,
      columnNumber: 1,
      analysisSource: 'LLM',
      confidence: 92,
      originalCode: 'START WITH manager_id IS NULL CONNECT BY PRIOR employee_id = manager_id',
      suggestedCode: 'WITH RECURSIVE emp_tree AS (SELECT employee_id, manager_id, 1 as level FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.employee_id, e.manager_id, t.level + 1 FROM employees e JOIN emp_tree t ON e.manager_id = t.employee_id)'
    });
  }
  
  return mockProblems;
};